package sgd;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class LR {
	
	public static double[] trainLR(String yfile, String[] infile){
		double constant = 0;
		double[] w = new double[infile.length];
		double rmse = 0;
		double lastrmse = 0;
		
		double lrate = 0.001;
		double r = 0.0015;
		System.out.println("begin training lr...");
		for (int e = 0; (e < 30) || 
				((e < 50) && (lastrmse > rmse + 0.0001)) ;e++){
			lastrmse = rmse;
			rmse = 0;
			try{
				BufferedReader ybr = new BufferedReader(new FileReader(yfile));
				BufferedReader[] br = new BufferedReader[infile.length];
				for (int i = 0; i < br.length; i++){
					br[i] = new BufferedReader(new FileReader(infile[i]));
				}
				String line;
				int lineNum = 0;
				double[] f = new double[infile.length];
				while ((line = ybr.readLine()) != null){
					if (lineNum % 1000000 == 0)
						System.out.println(lineNum);
					lineNum++;
					double y = constant;
					for (int j = 0; j < w.length; j++){
						f[j] = Double.parseDouble(br[j].readLine());
						y += f[j]*w[j];
					}
					if (y > 1) y = 1;
					if (y < 0) y = 0;
					double err = Double.parseDouble(line) - y;
					rmse+= err*err;
					constant += lrate*(err - r * constant);
					for (int j = 0; j < w.length; j++)
						w[j] += lrate*(err*f[j] - r * w[j]);
				}
				rmse = Math.sqrt(rmse/lineNum);
				System.out.println(rmse);
				
				
			}catch(Exception ecp){
				ecp.printStackTrace();
			}
		}
		System.out.println(constant);
		return w;
	}
	
	public static void outtrainLR(String yfile, String[] infile) {
//		double[] w = { 0.05693068897024272, 0.01756600318431403,
//				0.21024908883268797, 0.024272942581377265, 0.09185681735552478,
//				0.0720352952169376, 0.4316594388750829, 0.052130661498737074,
//				0.025887917332698025, 0.026318406096050864 };
		double[] w = {0.34402360484701416,
				0.07680313820844657};
		
		try {
			BufferedReader ybr = new BufferedReader(new FileReader(yfile));
			BufferedReader[] br = new BufferedReader[infile.length];
			for (int i = 0; i < br.length; i++) {
				br[i] = new BufferedReader(new FileReader(infile[i]));
			}
			String line;
			int lineNum = 0;
			double[] f = new double[infile.length];
			BufferedWriter bw = new BufferedWriter(new FileWriter("merge_out_c.csv"));
			lineNum = 0;
			while ((line = ybr.readLine()) != null) {
				if (lineNum % 1000000 == 0)
					System.out.println(lineNum);
				lineNum++;
				double y = 0.019116016843199947;
				for (int j = 0; j < w.length; j++) {
					f[j] = Double.parseDouble(br[j].readLine());
					y += f[j] * w[j];
				}
				if (y > 1)
					y = 1;
				if (y < 0)
					y = 0;
				bw.write(String.valueOf(y));
				bw.write("\n");
			}
			bw.flush();
			bw.close();
		} catch (Exception ecp) {
			ecp.printStackTrace();
		}
	}

}
